package org.adorsys.aderp.aderplogin.client.hessian;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.adorsys.aderp.aderplogin.client.basic.ClientBasicAuthenticator;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.util.Assert;

public class HessianBasicAuthFilter implements Filter, InitializingBean{
	
	private ClientBasicAuthenticator clientBasicAuthenticator;
	
	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		UsernamePasswordAuthenticationToken authenticate = clientBasicAuthenticator.authenticate((HttpServletRequest) request);
	
		if (authenticate==null) {
			throw new BadCredentialsException("Wrong client secret");
		}
        chain.doFilter(request, response);
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void afterPropertiesSet() throws Exception {
        Assert.notNull(clientBasicAuthenticator, "A ClientBasicAuthenticator must be set");
	}

	public void setClientBasicAuthenticator(
			ClientBasicAuthenticator clientBasicAuthenticator) {
		this.clientBasicAuthenticator = clientBasicAuthenticator;
	}

	
}
